package com.xxw.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxw.yygh.common.exception.YyghException;
import com.xxw.yygh.enums.OrderStatusEnum;
import com.xxw.yygh.enums.PaymentStatusEnum;
import com.xxw.yygh.hosp.client.ScheduleFeignClient;
import com.xxw.yygh.model.order.OrderInfo;
import com.xxw.yygh.model.order.PaymentInfo;
import com.xxw.yygh.model.user.Patient;
import com.xxw.yygh.mq.MqConst;
import com.xxw.yygh.mq.RabbitService;
import com.xxw.yygh.order.dao.OrderInfoDao;
import com.xxw.yygh.order.service.OrderInfoService;
import com.xxw.yygh.order.service.PaymentInfoService;
import com.xxw.yygh.order.service.WeiPayService;
import com.xxw.yygh.order.utils.HttpRequestHelper;
import com.xxw.yygh.user.client.PatientFeignClient;
import com.xxw.yygh.vo.hosp.ScheduleOrderVo;
import com.xxw.yygh.vo.msm.MsmVo;
import com.xxw.yygh.vo.order.OrderCountQueryVo;
import com.xxw.yygh.vo.order.OrderCountVo;
import com.xxw.yygh.vo.order.OrderMqVo;
import com.xxw.yygh.vo.order.OrderQueryVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表(OrderInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-03-07 14:37:08
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoDao, OrderInfo> implements OrderInfoService {

    @Resource
    private ScheduleFeignClient scheduleFeignClient;

    @Resource
    private PatientFeignClient patientFeignClient;

    @Resource
    private RabbitService rabbitService;

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private PaymentInfoService paymentInfoService;

    @Resource
    private WeiPayService weiPayService;

    //生成订单
    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //1.先根据scheduleId获取医生排班信息
        ScheduleOrderVo scheduleOrderVo = scheduleFeignClient.getScheduleById(scheduleId);

        if (new DateTime(scheduleOrderVo.getStopTime()).isBeforeNow()){
            throw new YyghException(20001,"超过挂号截止时间");
        }
        //2.先根据patientId获取就诊人信息
        Patient patient = patientFeignClient.getPatientById(patientId);

        //3.从平台请求第三方医院，确认当前用户能否挂号
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",scheduleOrderVo.getHoscode());
        paramMap.put("depcode",scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",scheduleOrderVo.getReserveDate());
        paramMap.put("reserveTime",scheduleOrderVo.getReserveTime());
        paramMap.put("amount",scheduleOrderVo.getAmount());

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");

        if (jsonObject != null && jsonObject.getInteger("code") == 200){
            JSONObject data = jsonObject.getJSONObject("data");

            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserId(patient.getUserId());
            String outTradeNo = System.currentTimeMillis()+""+new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);

            BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
            orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
            orderInfo.setPatientId(patient.getId());
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            orderInfo.setHosRecordId(data.getString("hosRecordId"));
            orderInfo.setNumber(data.getInteger("number"));
            orderInfo.setFetchTime(data.getString("fetchTime"));
            orderInfo.setFetchAddress(data.getString("fetchAddress"));

            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());

            //3.2 如果返回能挂号，就把获取到的医生排班信息、就诊人信息及第三方医院返回的信息都添加到order_info表中
            baseMapper.insert(orderInfo);
            //3.3 更新平台上对应医生的剩余可预约数
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            //int reservedNumber = data.getIntValue("reservedNumber");
            int availableNumber = data.getIntValue("availableNumber");
            orderMqVo.setAvailableNumber(availableNumber);

            //消息对象
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(patient.getPhone());
            msmVo.setTemplateCode("您已经预约了上午${time}点的${name}医生的号，不要迟到！");
            Map<String, Object> msmMap = new HashMap<>();
            msmMap.put("time",scheduleOrderVo.getReserveDate()+""+scheduleOrderVo.getReserveTime());
            msmMap.put("name","xxx");
            msmVo.setParam(msmMap);

            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
            
            //3.4 给就诊人发送短信提醒
            //4.返回订单id
            return orderInfo.getId();

        }else {
            //3.1 如果返回不能挂号，直接抛出异常
            throw new YyghException(20001,"号源已满");
        }


    }

    @Override
    public Page<OrderInfo> getOrderInfoPage(Integer pageNum, Integer pageSize, OrderQueryVo orderQueryVo) {
        Page page = new Page(pageNum, pageSize);
        QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();

        Long userId = orderQueryVo.getUserId();//用户id
        String outTradeNo = orderQueryVo.getOutTradeNo();//订单号
        String keyword = orderQueryVo.getKeyword();//医院名称
        Long patientId = orderQueryVo.getPatientId();//就诊人id
        String orderStatus = orderQueryVo.getOrderStatus();//订单状态
        String reserveDate = orderQueryVo.getReserveDate();//预约日期
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        if (!StringUtils.isEmpty(userId)) {
            orderInfoQueryWrapper.eq("user_id",userId);
        }
        if (!StringUtils.isEmpty(keyword)) {
            orderInfoQueryWrapper.like("hosname",keyword);
        }
        if (!StringUtils.isEmpty(outTradeNo)) {
            orderInfoQueryWrapper.eq("outTrade_no",outTradeNo);
        }
        if (!StringUtils.isEmpty(patientId)) {
            orderInfoQueryWrapper.eq("patient_id",patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            orderInfoQueryWrapper.eq("order_status",orderStatus);
        }
        if (!StringUtils.isEmpty(reserveDate)) {
            orderInfoQueryWrapper.ge("reserve_date",reserveDate);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            orderInfoQueryWrapper.ge("create_time",createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            orderInfoQueryWrapper.le("create_time",createTimeEnd);
        }

        Page<OrderInfo> page1 = baseMapper.selectPage(page, orderInfoQueryWrapper);
        page1.getRecords().stream().forEach(item->{
            this.packageOrderInfo(item);
        });

        return page1;

    }

    @Override
    public OrderInfo detail(Long orderId) {

        OrderInfo orderInfo = baseMapper.selectById(orderId);
        this.packageOrderInfo(orderInfo);
        return orderInfo;
    }

    @Transactional // 事务控制
    @Override
    public void paySuccess(Long orderId,Map<String,String> map) {
        //更新订单表的订单状态
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderInfoService.updateById(orderInfo);
        //更新支付记录表的支付状态
        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        updateWrapper.set("trade_no",map.get("transaction_id"));//微信支付订单号
        updateWrapper.set("payment_status", PaymentStatusEnum.PAID.getStatus());
        updateWrapper.set("callback_time",new Date());
        updateWrapper.set("callback_content", JSONObject.toJSONString(map));
        paymentInfoService.update(updateWrapper);
    }

    @Override
    public void cancelOrder(Long orderId) {
        //1.确定当前取消预约的时间 和 挂号订单的取消预约截止时间 对比
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if (quitTime.isBeforeNow()){
            //如果超过了则抛出异常不让用户取消
            throw new YyghException(20001,"超过了退号的截止时间");
        }

        Map<String, Object> hospitalParamMap = new HashMap<>();
        hospitalParamMap.put("hoscode",orderInfo.getHoscode());
        hospitalParamMap.put("hosRecordId",orderInfo.getHosRecordId());

        //2.平台请求第三方医院，通知第三方医院，该用户已取消
        JSONObject jsonObject = HttpRequestHelper.sendRequest(hospitalParamMap, "http://localhost:9998/order/updateCancelStatus");
        if (jsonObject == null || jsonObject.getIntValue("code") != 200) {
            //2.1第三方医院不同意取消，抛出异常，不能取消
            throw new YyghException(20001,"取消失败");
        }

        //3.判断用户是否对当前挂号订单是否已支付
        if (orderInfo.getOrderStatus() == OrderStatusEnum.PAID.getStatus()){
            //3.1如果已支付，退款
            boolean flag = weiPayService.refund(orderId);
            if (!flag) {
                throw new YyghException(20001,"退款失败");
            }

        }

        //4.更新订单状态 及支付记录表的支付状态
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);

        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderInfo.getId());
        updateWrapper.set("payment_status", PaymentStatusEnum.REFUND.getStatus());

        paymentInfoService.update(updateWrapper);

        //5.更新医生的剩余可预约数信息
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());

        orderMqVo.setMsmVo(msmVo);
        //6.给就诊人发送短信提示
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);

    }

    //就医提醒
    @Override
    public void patientRemind() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",-1);//订单状态不等于-1
        List<OrderInfo> orderInfos = baseMapper.selectList(queryWrapper);

        for (OrderInfo orderInfo : orderInfos) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS,MqConst.ROUTING_SMS_ITEM,msmVo);
        }
    }

    @Override
    public Map<String, Object> statistics(OrderCountQueryVo orderCountQueryVo) {

        List<OrderCountVo> countVoList =baseMapper.statistics(orderCountQueryVo);

        List<String> dateList = countVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> countList = countVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        HashMap<String, Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("countList",countList);

        return map;
    }

    private void packageOrderInfo(OrderInfo item) {
        item.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(item.getOrderStatus()));
    }
}

